using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using Vin.Extension.Framework.Wechat.Pay.Adapter;
using Vin.Extension.Framework.Wechat.Pay.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssemblyCategory;
using Vin.Tool.Core.JsonCategory;
using Vin.Tool.Core.NetCategory;

namespace Vin.Extension.Framework.Wechat.Pay;

public class WechatPayEndPoint
{
    private static List<IWechatPayNotify> Callbacks => AssemblyTool.GetTypes<IWechatPayNotify>()
        .Select(Activator.CreateInstance)
        .Cast<IWechatPayNotify>()
        .ToList();

    public static void UseAlipayNotify(WebApplication app, string notifyUrl)
    {
        app.MapPost(notifyUrl, async (HttpRequest request) =>
        {
            var context = request.HttpContext;
            var wxPayClient = VinApp.GetRequiredServiceByHttpContext<VinWxPayV3BaseService>();
            var logger = VinApp.GetRequiredServiceByHttpContext<ILogger<WechatPayEndPoint>>();
            var body = await context.ReadToString();
            var callbackModel = wxPayClient.WxPayClient?.DeserializeEvent(body);
            if (callbackModel == null)
            {
                logger.LogError("微信支付成功回调签名解析失败: {0}", context.FormDictionary().ToCamelCaseJson());
            }
            else
            {
                foreach (var wechatPayNotify in Callbacks
                             // 忽略大小写
                             .Where(x => string.Equals(x.EventType, callbackModel.EventType,
                                 StringComparison.OrdinalIgnoreCase))
                             // 按照 Order 排序
                             .OrderBy(m => m.Order))
                {
                    await wechatPayNotify.NotifyAsync(context, callbackModel);
                }
            }

            return TypedResults.Content("success");
        });
    }
}